<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.code" clearable class="filter-item" style="width: 200px;"
        :placeholder="$t('请输入code')" />
      <!--      <el-input v-model="listQuery.mobile" clearable class="filter-item" style="width: 200px;" placeholder="请输入手机号"/>-->
      <region :options="regionSearchOptions"></region>
      <el-button class="filter-item" type="info" plain1 icon="el-icon-search" @click="handleFilter">{{ $t('Search') }}
      </el-button>
      <el-button v-permission="['GET /admin/p/config_tax_add']" class="filter-item" type="warning" plain1 icon="el-icon-circle-plus"
        @click="handleAdd">{{ $t('Add') }}</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" :element-loading-text="$t('Searching')" border fit
      highlight-current-row>
      <el-table-column type="index" :index="getIndex" width="50"></el-table-column>
      <!--      <el-table-column align="center" width="100px" :label="$t('Member_ID')" prop="id" sortable="custom"/>-->

      <el-table-column align="center" :label="$t('区域名')" prop="regionNameCn" sortable="custom">
        <template slot="header" slot-scope="{row}">
          {{$t('区域名')}}
          <i class="el-icon-location"></i>
        </template>
        <template slot-scope="scope">
          <el-tag type="success">{{ scope.row.name || scope.row.regionNameCn || scope.row.regionNameEn }}</el-tag>
        </template>
      </el-table-column>

      <!--      <el-table-column align="center" :label="$t('税率名称')" prop="name" sortable="custom"/>-->

      <el-table-column align="center" :label="$t('税率代码')" prop="code" />

      <el-table-column align="center" :label="$t('税率值')" prop="value"></el-table-column>


      <el-table-column align="center" :label="$t('Activate_')" prop="enable">
        <template slot="header" slot-scope="{row}">
          {{$t('Activate_')}}
          <i class="el-icon-turn-off"></i>
        </template>
        <template slot-scope="scope">
          <el-switch v-model="scope.row.enable" v-permission="['GET /admin/p/config_tax_enable']"
            @change="handleEnable(scope.row)" :active-value="true" :nactive-value="false" active-color="#69EE11"
            inactive-color="#E6E61A" />
        </template>
      </el-table-column>


      <el-table-column align="center" :label="$t('Operate')" width="300" class-name="small-padding fixed-width">
        <template slot="header" slot-scope="{row}">
          {{$t('Operate')}}
          <i class="el-icon-setting"style="color: #d35e32"></i>
        </template>
        <template slot-scope="scope">
          <el-button v-permission="['GET /admin/p/config_tax_edit']" type="primary" icon="el-icon-edit" circle plain1
            @click="handleEdit(scope.row)"></el-button>
          <el-button v-permission="['DELETE /admin/p/config_tax_delete']" type="danger" icon="el-icon-delete" circle plain1
            @click="handleDelete(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
      @pagination="getTaxes" />

    <!-- 创建、编辑税费对话框 -->
    <el-dialog :visible.sync="taxDialogVisible" :title="dialogTitle">
      <el-form ref="taxForm" :model="taxForm" :rules="rules" status-icon label-position="left" label-width="200px"
        style="width: 500px; margin-left:50px;">
        <el-form-item :label="$t('区域')" prop="regionId">
          <Region :options="regionOptions"  v-if="taxDialogVisible"></Region>
        </el-form-item>
        <el-form-item :label="$t('税率代码')" prop="code">
          <el-input v-model="taxForm.code" :placeholder="$t('税率代码')">
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('税率值')" prop="value">
          <el-input v-model.number="taxForm.value" :placeholder="$t('税率值')">
            <template slot="append"> {{ $t('%') }}</template>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('Activate?')" prop="enable">
          <el-checkbox v-model="taxForm.enable" :label="$t('Activate_')"></el-checkbox>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button plain1 round icon="el-icon-error" @click="taxDialogVisible = false">{{ $t('Cancel') }}</el-button>
        <el-button v-if="dialogType == 1" plain1 round icon="el-icon-success" type="primary" @click="taxConfirm">{{ $t('Confirm') }}</el-button>
        <el-button v-if="dialogType == 2" plain1 round icon="el-icon-success" type="primary" @click="taxUpdate">{{ $t('Confirm') }}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import Region from '@/components/Region'
import { listTaxes, createTax, deleteTax, updateTax, enableTax } from '@/api/tax'
import { getParentIds } from '@/api/region'
import BackToTop from '@/components/BackToTop'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
export default {
  name: "configTax",
  components: {
    Region, BackToTop, Pagination,
  },
  data() {
    return {
      listLoading: true,
      total: 0,
      listQuery: {
        page: 1,
        limit: 20,
        code: undefined,
        regionId: undefined,
        sort: 'add_time',
        order: 'desc'
      },
      typeDic: ['', this.$t('国税'), this.$t('省税'), this.$t('地方税')],
      dialogTitle: this.$t('编辑'),
      dialogType: 1,
      taxDialogVisible: false,
      taxForm: {},
      list: [],
      regionOptions: {},
      regionSearchOptions: {},
      rules: {
        // regionId: [
        //   { required: true, message: this.$t('不能为空'), trigger: 'blur' }
        // ],
        code: [
          { required: true, message: this.$t('不能为空'), trigger: 'blur' }
        ],
        type: [
          { required: true, message: this.$t('不能为空'), trigger: 'blur' }
        ],
        value: [
          { required: true, message: this.$t('不能为空'), trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getTaxes()
  },
  methods: {
    getTaxes() {
      listTaxes(this.listQuery)
        .then(response => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.getTaxes()
    },
    taxConfirm() {
      if (!this.regionOptions.regionIds || this.regionOptions.regionIds.length == 0) {
        this.$notify.error({
          title: this.$t('Failed'),
          message: this.$t('请选择区域地址')
        })
        return;
      }
      this.$refs['taxForm'].validate((valid) => {
        if (valid) {
          let regionIds = this.regionOptions.regionIds;
          this.taxForm.firstRegionId = regionIds[0]
          if (regionIds.length > 1) {
            this.taxForm.secondRegionId = regionIds[1]
          } else {
            this.taxForm.secondRegionId = this.taxForm.firstRegionId
          }

          if (regionIds.length > 2) {
            this.taxForm.regionId = regionIds[2]
          } else {
            this.taxForm.regionId = this.taxForm.secondRegionId
          }

          createTax(this.taxForm).then(response => {
            this.taxDialogVisible = false
            this.$notify.success({
              title: this.$t('Success!'),
              message: this.$t('Success!')
            })
            this.getTaxes()
          }).catch(response => {
            this.$notify.error({
              title: this.$t('Failed'),
              message: this.$t(response.data.errmsg)
            })
          })
        }
      })
    },
    taxUpdate() {
      this.$refs['taxForm'].validate((valid) => {
        if (valid) {
          if (!this.regionOptions.regionIds || this.regionOptions.regionIds.length == 0) {
            this.$notify.error({
              title: this.$t('Failed'),
              message: this.$t('请选择区域地址')
            })
            return;
          }
          let regionIds = this.regionOptions.regionIds;
          this.taxForm.firstRegionId = regionIds[0]
          if (regionIds.length > 1) {
            this.taxForm.secondRegionId = regionIds[1]
          } else {
            this.taxForm.secondRegionId = this.taxForm.firstRegionId
          }

          if (regionIds.length > 2) {
            this.taxForm.regionId = regionIds[2]
          } else {
            this.taxForm.regionId = this.taxForm.secondRegionId
          }
          updateTax(this.taxForm).then(response => {
            this.taxDialogVisible = false
            this.$notify.success({
              title: this.$t('Success!'),
              message: this.$t('Success!')
            })
            this.getTaxes()
          }).catch(response => {
            this.$notify.error({
              title: this.$t('Failed'),
              message: this.$t(response.data.errmsg)
            })
          })
        }
      })
    },
    handleAdd() {
      this.dialogType = 1
      this.dialogTitle = this.$t('Add')
      this.taxDialogVisible = !this.taxDialogVisible
      this.resetForm()
    },
    resetForm() {
      this.taxForm = {}
    },
    async handleEdit(row) {
      await getParentIds(row.regionId).then(response => {
        this.regionOptions.regionIds = response.data.data
        this.dialogType = 2
        this.dialogTitle = this.$t('Edit')
        this.taxDialogVisible = !this.taxDialogVisible
        this.taxForm = row
      })
    },
    handleDelete(row) {
      deleteTax(row.id).then(response => {
        this.taxDialogVisible = false
        this.$notify.success({
          title: this.$t('Success!'),
          message: this.$t('Success!')
        })
        this.getTaxes()
      }).catch(response => {
        this.$notify.error({
          title: this.$t('Failed'),
          message: this.$t(response.data.errmsg)
        })
      })
    },
    handleEnable(row) {
      enableTax(row).then(response => {
        this.taxDialogVisible = false
        this.$notify.success({
          title: this.$t('Success!'),
          message: this.$t('Success!')
        })
      }).catch(response => {
        this.$notify.error({
          title: this.$t('Failed'),
          message: this.$t(response.data.errmsg)
        })
      })
    },
    getIndex(index) {
      return (index + 1) + (this.listQuery.page - 1) * this.listQuery.limit;
    }
  },
  watch: {
    'regionOptions.regionIds': function (newVal, oldVal) {
      // if(newVal && newVal.length > 0){
      this.taxForm.regionId = this.regionOptions.regionIds[this.regionOptions.regionIds.length - 1]
      // }
    },
    'regionSearchOptions.regionIds': function (newVal, oldVal) {
      if (newVal && newVal.length > 0) {
        this.listQuery.regionId = this.regionSearchOptions.regionIds[this.regionSearchOptions.regionIds.length - 1]
      } else {
        this.listQuery.regionId = undefined
      }
    }
  }
}
</script>

<style scoped>

</style>
